<?php
namespace Home\Controller;
use Think\Controller;
class CommonController extends EmchatController {
	private $key = 'pengrun123456';
	/**
     * [全局token验证]
     * @return [type] [json]
     */
    public function accesstoken(){
		$key = $this->key; //公钥
        $token = $_POST['token'];
		if(!$token) returnApiError(40001,'缺少token参数');
		$data = json_decode($this->decrypt($token,$key),true);
		$time = intval($data['time']);
		if(($time+7200) < time()) returnApiError(40002,'token时间过期');  
		$appid = intval($data['appid']);
		$appkey = $data['appkey'];
		$Model = M('Token');
		$where['appid'] = $appid;
		$where['appkey'] = $appkey;
		$result = $Model->where($where)->find();
		if(!$result){
			returnApiError(1,'验证失败，token不正确');  
		}
    }

    /**
     * 用户token验证
     */
    public function usertoken($uid){
        $usertoken = I('post.usertoken');
        $model = M('member');
        $data = $model->field('member_id,member_name')->find($uid);
        if(!$data){
            returnApiError(1,'用户不存在');
        }
        $data_token = md5($data['member_id'].$data['member_name']);
        if($usertoken != $data_token){
            returnApiError(1,'usertoken参数不正确');
        }
    }

	/**
     * [token des加密]
     * @return [type] [json]
     */
	function encrypt($input, $key)
    {
        $input = str_replace("n", "", $input);
        $input = str_replace("t", "", $input);
        $input = str_replace("r", "", $input);
        $key = substr(md5($key), 0, 24);
        $td = mcrypt_module_open('tripledes', '', 'ecb', '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $encrypted_data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return trim(chop(base64_encode($encrypted_data)));
    }
    
    /**
     * [token des解密]
     * @return [type] [json]
     */
    function decrypt($input, $key)
    {
        $input = str_replace("n", "", $input);
        $input = str_replace("t", "", $input);
        $input = str_replace("r", "", $input);
        $input = trim(chop(base64_decode($input)));
        $td = mcrypt_module_open('tripledes', '', 'ecb', '');
        $key = substr(md5($key), 0, 24);
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $decrypted_data = mdecrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return trim(chop($decrypted_data));
    }
  
}